import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { ListeningMaterial } from '../models/ListeningMaterial';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';

// 音频文件上传
export const uploadAudio = async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: '没有上传文件' });
    }

    const file = req.file;
    const fileExt = path.extname(file.originalname);
    const fileName = `${uuidv4()}${fileExt}`;
    const filePath = path.join(__dirname, '../../uploads/audio', fileName);

    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../uploads/audio');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 移动文件到目标目录
    fs.renameSync(file.path, filePath);

    // 返回文件信息
    res.json({
      fileName,
      filePath: `/uploads/audio/${fileName}`,
      originalName: file.originalname,
      size: file.size,
      mimeType: file.mimetype
    });
  } catch (error) {
    res.status(500).json({ message: '文件上传失败', error });
  }
};

// 删除音频文件
export const deleteAudio = async (req: Request, res: Response) => {
  try {
    const { fileName } = req.params;
    const filePath = path.join(__dirname, '../../uploads/audio', fileName);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ message: '文件不存在' });
    }

    // 删除文件
    fs.unlinkSync(filePath);

    // 检查是否有听力材料使用此音频
    const materialRepository = getRepository(ListeningMaterial);
    const materials = await materialRepository.find({
      where: { audioUrl: `/uploads/audio/${fileName}` }
    });

    // 更新使用此音频的材料
    for (const material of materials) {
      material.audioUrl = '';
      await materialRepository.save(material);
    }

    res.status(204).send();
  } catch (error) {
    res.status(500).json({ message: '文件删除失败', error });
  }
};

// 获取音频文件列表
export const getAudioList = async (req: Request, res: Response) => {
  try {
    const uploadDir = path.join(__dirname, '../../uploads/audio');
    if (!fs.existsSync(uploadDir)) {
      return res.json([]);
    }

    const files = fs.readdirSync(uploadDir);
    const fileList = files.map(file => {
      const stats = fs.statSync(path.join(uploadDir, file));
      return {
        fileName: file,
        filePath: `/uploads/audio/${file}`,
        size: stats.size,
        createdAt: stats.birthtime
      };
    });

    res.json(fileList);
  } catch (error) {
    res.status(500).json({ message: '获取文件列表失败', error });
  }
}; 